package com.css.fxfzypg.modules.model.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.service.IntensityRelationService;
import com.css.fxfzypg.modules.SettingSeismic.service.SettingSeismicService;
import com.css.fxfzypg.modules.baseData.entity.*;
import com.css.fxfzypg.modules.baseData.service.HouseService;
import com.css.fxfzypg.modules.model.entity.DataPbeIntStrArea;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultupload.service.ResultTotalService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.BeanUtil;
import com.css.fxfzypg.modules.model.entity.DataPbeLosses;
import com.css.fxfzypg.modules.model.entity.EconomicLosses;
import com.css.fxfzypg.modules.model.repository.CasualtyRepository;
import com.css.fxfzypg.modules.model.repository.EconomicLossesRepository;
import com.css.fxfzypg.modules.model.service.EconomicLossesService;
import com.css.fxfzypg.modules.model.vo.EconomicVO;
import com.css.fxfzypg.modules.preAssessResult.entity.Vulnerability;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preAssessResult.vo.LossesVulnerabilityVO;
import com.css.fxfzypg.modules.preAssessResult.vo.StructuralProportionVo;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultDetailsEntity;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.geotools.data.FeatureWriter;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Dbj
 * @date 2022年10月06日  15:14
 */
@Service
public class EconomicLossesServiceImpl implements EconomicLossesService {

    @Resource
    private EconomicLossesRepository economicLossesRepository;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    SUserService sUserService;

    @Resource
    private SysRoleService roleService;

    @Resource
    private HouseService houseService;

    @Resource
    private SysAreaService areaService;

    @Resource
    ResultTotalService resultTotalService;

    @Resource
    PreAssessResultService preAssessResultService;

    @Resource
    private CasualtyRepository casualtyRepository;
    @Resource
    IntensityRelationService intensityRelationService;
    @Resource
    SettingSeismicService settingSeismicService;
    public static final int BATCH_SIZE = 1000;
    @Resource
    PreAssessTaskService preAssessTaskService;
    @Value("${image.localDir}")
    private String localDir;

    @Override
    public Map<String, Object> getPage(EconomicVO vo, int curPage, int pageSize) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        String userId = PlatformSessionContext.getUserID();
        vo.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
        String roleByUserId = roleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            if (roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)) {
                vo.setNation(true);
            }
        }
        if (vo.getNation() == null) {
            vo.setNation(false);
        }
        Map<String, Object> page = economicLossesRepository.findPage(vo, curPage, pageSize);
        List<EconomicLosses> list = (List<EconomicLosses>) page.get("rows");
        for (EconomicLosses economicLosses : list) {
            economicLosses.setProvince(areaMap.get(economicLosses.getProvince()));
            if (!"全部".equals(economicLosses.getCity())) {
                StringBuffer buffer = new StringBuffer();
                List<String> cityList = Arrays.asList(economicLosses.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                economicLosses.setCity(cityName.substring(0, cityName.length() - 1));
            }
        }
        page.put("rows", list);
        return page;
    }

    @Override
    public EconomicLosses getModelById(String id) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        EconomicLosses economicLosses = economicLossesRepository.getModelById(id);
        economicLosses.setProvince(areaMap.get(economicLosses.getProvince()));
        if (!"全部".equals(economicLosses.getCity())) {
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(economicLosses.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            economicLosses.setCity(cityName.substring(0, cityName.length() - 1));
        }
//        CasualtyVO vo = new CasualtyVO();
//        BeanUtil.copy(casualty,vo);
        return economicLosses;
    }

    @Override
    public EconomicLosses getDefaultModel() {
        return economicLossesRepository.getDefaultModel();
    }

    @Override
    public List<EconomicLosses> getByDivision(String province, String city, int isNa) {
        return economicLossesRepository.getByDivision(province, city, isNa);
    }

    @Override
    public EconomicLosses getModelByIdForCopy(String id) {
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        EconomicLosses economicLosses = economicLossesRepository.getModelById(id);
        economicLosses.setModelName("");
        economicLosses.setIsDefault("0");
        economicLosses.setCity("");
        economicLosses.setProvince("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        economicLosses.setCreateUserId(userId);
        economicLosses.setCreateUserName(sUser.getUserName());
        economicLosses.setOrgId(sUser.getOrgId());
        economicLosses.setOrgName(orgMap.get(sUser.getOrgId()));
        economicLosses.setIsValid(YNEnum.Y.toString());
        return economicLosses;
    }

    @Override
    public void save(EconomicLosses economicLosses) {
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        String userId = PlatformSessionContext.getUserID();
        economicLosses.setId(UUIDGenerator.getUUID());
        economicLosses.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        economicLosses.setCreateUserName(sUser.getUserName());
        economicLosses.setCreateTime(new Date());
        economicLosses.setOrgId(sUser.getOrgId());
        String orgName = orgMap.get(sUser.getOrgId());
        economicLosses.setOrgName(orgName);
        economicLosses.setIsValid(YNEnum.Y.toString());
        //获取省code
        String areaCode = areaService.getDivisionCodeById(economicLosses.getProvince());
        areaCode = (String) JSONObject.parse(areaCode);
        economicLosses.setProvinceCode(areaCode);
        economicLossesRepository.save(economicLosses);
    }

    @Override
    public void update(EconomicLosses economicLosses) {
        EconomicLosses ec = economicLossesRepository.getModelById(economicLosses.getId());
        String userId = PlatformSessionContext.getUserID();
        if (!userId.equals(ec.getCreateUserId())) {
            throw new RuntimeException("修改失败，只能修改自己创建的模型");
        }
        BeanUtil.copy(economicLosses, ec);
        economicLosses.setUpdateUserId(userId);
        economicLosses.setUpdateTime(new Date());
        economicLossesRepository.update(economicLosses);
    }

    @Override
    public void delete(String id) {
        EconomicLosses economicLosses = economicLossesRepository.getModelById(id);
        String userId = PlatformSessionContext.getUserID();
        if (!userId.equals(economicLosses.getCreateUserId())) {
            throw new RuntimeException("删除失败，只能删除自己创建的模型");
        }
        economicLossesRepository.delete(userId, new Date(), id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse savePbeLosses(String modeId, String taskId, String tab,String range) throws Exception {
        RestResponse restResponse = null;
        try {
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
                return RestResponse.fail(503, "该任务的正在被其他人计算，请稍后再操作！！！");
            }
            redisTemplate.opsForValue().set(taskId, "4-1");
            Long start = System.currentTimeMillis();
            economicLossesRepository.deleteByTaskId(taskId);

            SeismicIntensityRelation byTaskId = intensityRelationService.getByTaskId(taskId);
            if (byTaskId == null) {
                restResponse = RestResponse.fail(503, "请生成该任务下的地震影响场");
                return restResponse;
            }

            EconomicLosses model = economicLossesRepository.getModelById(modeId);
            if (PlatformObjectUtils.isEmpty(model)) {
                restResponse = RestResponse.fail(503, "请选择人员伤亡模型");
                return restResponse;
            }
            //根据任务id取所有影响场和任务区域的并集，作为最大区域查格网
            List<DataPbeIntStrArea> pbeList = casualtyRepository.getDataPbeIntStrAreaByTaskId(taskId, "");
            if (PlatformObjectUtils.isEmpty(pbeList)) {
                restResponse = RestResponse.fail(503, "请先计算该任务下的人员伤亡！");
                return restResponse;
            }
            PreAssessTaskEntity byId = preAssessTaskService.getById(taskId);
            String taskDistrict = byId.getTaskDistrict();

            String province = "";//省
            String city = "";//市
            String county = "";//县
            String town = "";//镇
            StructuralProportionVo structuralProportion = null;//人口与建筑物数据的VO
            HouseEntity house = null;
            List<DataPbeLosses> lossesList = new ArrayList<>();
            for (int k = 0; k < pbeList.size(); k = k + 25) {
                DataPbeIntStrArea entity = pbeList.get(k);
                String type1 = entity.getType1();//0:任务范围内的格网；1:任务范围外，影响场范围内的格网
                //同一个省市县镇只查一次
                if (!entity.getProvince().equals(province) || !entity.getCity().equals(city) || !entity.getCounty().equals(county) || !town.equals(entity.getTown())) {
                    structuralProportion = preAssessResultService.getStructuralProportion(entity.getProvince(),
                            entity.getCity(), entity.getCounty(), entity.getTown(), entity.getTownorcontry());
                } else {
                    if (PlatformObjectUtils.isEmpty(structuralProportion)) {
                        structuralProportion = preAssessResultService.getStructuralProportion(entity.getProvince(),
                                entity.getCity(), entity.getCounty(), entity.getTown(), entity.getTownorcontry());
                    }
                }
                //此时人口与建筑物为空，则区县级的人口与建筑物为空
                if (PlatformObjectUtils.isEmpty(structuralProportion)) {
                    //tab1为true表示该格网在该任务区域内
                    boolean tab1 = false;
                    for (String s : taskDistrict.split("、")) {
                        if (s.equals(entity.getProvince() + "-" + entity.getCity() + "-" + entity.getCounty())) {
                            tab1 = true;
                            break;
                        } else if (s.equals(entity.getProvince() + "-" + entity.getCity())) {
                            tab1 = true;
                            break;
                        } else if (s.equals(entity.getProvince())) {
                            tab1 = true;
                            break;
                        }
                    }
                    if (tab1 && "0".equals(type1)) {
                        restResponse = RestResponse.fail(503,
                                "未获取到" + entity.getProvince() + "、" + entity.getCity() + "、" + entity.getCounty() + "的人口和建筑物概况数据！");
                        return restResponse;
                    } else if ((!tab1 && "0".equals(type1) && !tab.contains("1")) || "1".equals(type1) && !tab.contains("1")) {
                        if (range.equals("0")){
                           JSONObject map = new JSONObject();
                        map.put("tab", tab + "1");
                        restResponse = RestResponse.fail(501, "未获取到" + entity.getProvince() + "、" + entity.getCity() +
                                "、" + entity.getCounty() + "的人口和建筑物概况数据,请确认是否继续进行计算！", map);
                        return restResponse;
                        }

                    }
                }
                //地区室内财产（元/每平米）
                BigDecimal dhpIndoorProperty = structuralProportion == null || structuralProportion.getDhpIndoorProperty() == null ?
                        BigDecimal.ZERO : structuralProportion.getDhpIndoorProperty();
                // if (dhpIndoorProperty==null){
                //     //tab1为true表示该格网在该任务区域内
                //                         boolean tab1 = false;
                //                         for (String s : taskDistrict.split("、")) {
                //                             if (s.equals(entity.getProvince() + "-" + entity.getCity() + "-" + entity.getCounty())) {
                //                                 tab1 = true;
                //                                 break;
                //                             } else if (s.equals(entity.getProvince() + "-" + entity.getCity())) {
                //                                 tab1 = true;
                //                                 break;
                //                             } else if (s.equals(entity.getProvince())) {
                //                                 tab1 = true;
                //                                 break;
                //                             }
                //                         }
                //                         if (tab1 && "0".equals(type1)) {
                //         return RestResponse.fail(503,"未获取到" + entity.getProvince() + "、" + entity.getCity() + "、" + entity.getCounty() + "的人口和建筑物概况数据的地区室内财产（元/每平米）！");
                //     } else if ((!tab1 && "0".equals(type1) && !tab.contains("2")) || "1".equals(type1) && !tab.contains("2")) {
                //         JSONObject map = new JSONObject();
                //         map.put("tab", tab+"2");
                //         return RestResponse.fail(501,"未获取到" + entity.getProvince() + "、" + entity.getCity() +
                //                 "、" + entity.getCounty() + "的人口和建筑物概况数据的地区室内财产（元/每平米）,请确认是否继续进行计算！",map);
                //     }
                // }
                //每个省市县只查询一次数据库
                if (!entity.getProvince().equals(province) || !entity.getCity().equals(city) || !entity.getCounty().equals(county)) {
                    house = houseService.getHouse(entity.getProvince(), entity.getCity(), entity.getCounty());
                    if (house == null) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(entity.getProvince() + "-" + entity.getCity() + "-" + entity.getCounty())) {
                                tab1 = true;
                                break;
                            } else if (s.equals(entity.getProvince() + "-" + entity.getCity())) {
                                tab1 = true;
                                break;
                            } else if (s.equals(entity.getProvince())) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (tab1 && "0".equals(type1)) {
                            restResponse = RestResponse.fail(503,
                                    "未获取到" + entity.getProvince() + "、" + entity.getCity() + "、" + entity.getCounty() + "的房屋造价信息！");
                            return restResponse;
                        } else if ((!tab1 && "0".equals(type1) && !tab.contains("3")) || "1".equals(type1) && !tab.contains("3")) {
                            if (range.equals("0")){
                                JSONObject map = new JSONObject();
                            map.put("tab", tab + "3");
                            restResponse = RestResponse.fail(501,
                                    "未获取到" + entity.getProvince() + "、" + entity.getCity() +
                                            "、" + entity.getCounty() + "的房屋造价信息,请确认是否继续进行计算！", map);
                            return restResponse;
                            }

                        }
                    }
                    // if (house.getHighHousePrice() == null) {
                    //     //tab1为true表示该格网在该任务区域内
                    //                         boolean tab1 = false;
                    //                         for (String s : taskDistrict.split("、")) {
                    //                             if (s.equals(entity.getProvince() + "-" + entity.getCity() + "-" + entity.getCounty())) {
                    //                                 tab1 = true;
                    //                                 break;
                    //                             } else if (s.equals(entity.getProvince() + "-" + entity.getCity())) {
                    //                                 tab1 = true;
                    //                                 break;
                    //                             } else if (s.equals(entity.getProvince())) {
                    //                                 tab1 = true;
                    //                                 break;
                    //                             }
                    //                         }
                    //                         if (tab1 && "0".equals(type1)) {
                    //         return RestResponse.fail("未获取到" + entity.getProvince() + "、" + entity.getCity() + "、" + entity.getCounty() + "的房屋造价信息！");
                    //    } else if ((!tab1 && "0".equals(type1) && !tab.contains("4")) || "1".equals(type1) && !tab.contains("4")) {
                    //         JSONObject map = new JSONObject();
                    //         map.put("tab", tab+"4");
                    //         return RestResponse.fail(500,"未获取到" + entity.getProvince() + "、" + entity.getCity() +
                    //                 "、" + entity.getCounty() + "的房屋造价信息,请确认是否继续进行计算！",map);
                    //     }
                    // }
                }
                //6-10代表5个地震烈度 要获取每个地震烈度的经济损失
                for (int i = 6; i < 11; i++) {
                    DataPbeLosses losses = new DataPbeLosses();
                    if (entity.getCoveredArea().compareTo(BigDecimal.ZERO) == 0) {
                        losses.setId(UUIDGenerator.getUUID()).setPbeId(entity.getPbeId()).setCoveredarea(entity.getCoveredArea())
                                .setPopulation(entity.getPopulation().intValue()).setDzIntentity("" + i).setTaskId(taskId).setGeomText(entity.getGeomText())
                                .setDirectLosses(new BigDecimal(0)).setOtherLosses(new BigDecimal(0)).setLifeLosses(new BigDecimal(0))
                                .setStructureLosses(new BigDecimal(0)).setIndoorLosses(new BigDecimal(0)).setStructureDirectLosses(new BigDecimal(0));
                    } else {
                        BigDecimal structureDirectLosses = new BigDecimal(0);
                        BigDecimal structureLossess = new BigDecimal(0);
                        BigDecimal indoorLossess = new BigDecimal(0);
                        Map<String, Object> map = new HashMap<>(10);
                        for (int j = 0; j < 9; j++) {
                            map.put("structureType", String.valueOf(j));
                            if (FxfzConstants.HIGH_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getHArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getHArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getHArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getHArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getHArea());
                            } else if (FxfzConstants.STEEL_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getSteelArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getSteelArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getSteelArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getSteelArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getSteelArea());
                            } else if (FxfzConstants.HNT_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getCArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getCArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getCArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getCArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getCArea());
                            } else if (FxfzConstants.ZH_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getBArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getBArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getBArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getBArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getBArea());
                            } else if (FxfzConstants.ZM_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getBmArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getBmArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getBmArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getBmArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getBmArea());
                            } else if (FxfzConstants.SOIL_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getSArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getSArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getSArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getSArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getSArea());
                            } else if (FxfzConstants.WOOD_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getWArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getWArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getWArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getWArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getWArea());
                            } else if (FxfzConstants.STONE_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getStArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getStArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getStArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getStArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getStArea());
                            } else if (FxfzConstants.OTHER_STRUCTURE.equals(String.valueOf(j))) {
                                //基本完好面积
                                map.put("basicArea", pbeList.get(k + (i - 6) * 5).getOArea());
                                //轻微破坏面积
                                map.put("slightArea", pbeList.get(k + (i - 6) * 5 + 1).getOArea());
                                //中等破坏面积
                                map.put("midArea", pbeList.get(k + (i - 6) * 5 + 2).getOArea());
                                //严重破坏面积
                                map.put("seriousArea", pbeList.get(k + (i - 6) * 5 + 3).getOArea());
                                //损坏面积
                                map.put("damageArea", pbeList.get(k + (i - 6) * 5 + 4).getOArea());
                            }
                            //获取每类建筑结构在每个地震烈度下的的建筑物结构经济损失和室内财产经济损失和建筑物直接经济损失
                            Map<String, BigDecimal> lossess = getStructureLossess(map, house, model, dhpIndoorProperty);
                            structureLossess = structureLossess.add(lossess.get("structure"));
                            indoorLossess = indoorLossess.add(lossess.get("indoor"));
                            structureDirectLosses = structureDirectLosses.add(lossess.get("direct"));
                        }
                        BigDecimal lifeLosses = structureDirectLosses.divide(model.getLifeRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(model.getLifeRatio2());
                        BigDecimal otherLosses = structureDirectLosses.divide(model.getOtherRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(model.getOtherRatio2());
                        BigDecimal directLosses = structureDirectLosses.add(lifeLosses).add(otherLosses).setScale(4, BigDecimal.ROUND_HALF_DOWN);
                        //此时获取到了某个格网9种建筑结构在某一地震烈度下的各种损失
                        losses.setId(UUIDGenerator.getUUID()).setPbeId(entity.getPbeId()).setCoveredarea(entity.getCoveredArea())
                                .setPopulation(entity.getPopulation().intValue()).setDzIntentity("" + i).setTaskId(taskId).setGeomText(entity.getGeomText())
                                .setDirectLosses(directLosses).setOtherLosses(otherLosses).setLifeLosses(lifeLosses)
                                .setStructureLosses(structureLossess.setScale(4, BigDecimal.ROUND_HALF_DOWN)).setIndoorLosses(indoorLossess.setScale(4, BigDecimal.ROUND_HALF_DOWN)).setStructureDirectLosses(structureDirectLosses.setScale(4, BigDecimal.ROUND_HALF_DOWN));
                    }
                    lossesList.add(losses);
                    //economicLossesRepository.saveDataPbeLosses(losses);
                }
                province = entity.getProvince();
                city = entity.getCity();
                county = entity.getCounty();
                town = entity.getTown();
            }
            System.out.println(lossesList.size() + "开始插入");
            //创建 data_pbe_losses 分区表
            economicLossesRepository.createLossesFqRel(taskId);
            //一次10万条
            int fromIndex = 0;
            int toIndex = BATCH_SIZE;
            while (fromIndex != lossesList.size()) {
                if (toIndex > lossesList.size()) {
                    toIndex = lossesList.size();
                }
                List<DataPbeLosses> list = lossesList.subList(fromIndex, toIndex);
                int insertcount = economicLossesRepository.saveDataPbeLossesList(list);
                System.out.println("插入成功" + insertcount);
                fromIndex = toIndex;
                toIndex += BATCH_SIZE;
                if (toIndex > lossesList.size())
                    toIndex = lossesList.size();
            }
            byTaskId.setButton3_status1("1");
            byTaskId.setModel3Id(modeId);
            byTaskId.setButton3_status2("0");
            intensityRelationService.updateSeismicIntensityRelation(byTaskId);
            System.out.println("保存时间:" + (System.currentTimeMillis() - start) / 1000);
            return ResponseCreator.createSuccessResponse("保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("生成地震影响场失败！");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResponse calculate(String taskId,String range) {
        RestResponse restResponse = null;
        try {
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
                return RestResponse.fail(503, "该任务的正在被其他人计算，请稍后再操作！！！");
            }
            redisTemplate.opsForValue().set(taskId, "4-2");
            Long start = System.currentTimeMillis();
            String userId = PlatformSessionUtils.getUserId();
            SeismicIntensityRelation byTaskId = intensityRelationService.getByTaskId(taskId);
            if (byTaskId == null) {
                return RestResponse.fail(503, "请生成该任务下的地震影响场");
            }
            //通过任务id获取到所有点的详情
            List<String> pointDetailList = settingSeismicService.getPointDetailByTaskId(taskId);
            //根据任务id获取任务下的所有的影响场（椭圆）下的同一个地震烈度的格网的经济损失数据  0
            //根据任务id获取任务与影响场重叠部分下的同一个地震烈度的格网的经济损失数据  1 range
            List<Map<String, Object>> mapList = economicLossesRepository.getPbeLossesByTaskId(taskId,range);
            //pbeId,area,directLosses,longitude,latitude,earthquakeLevel,angle,earthquakeId
            if (PlatformObjectUtils.isEmpty(mapList)) {
                return RestResponse.fail(503, "计算失败,该任务尚未生成影响场!");
            }
            //获取到同一个设定地震点下不同影响场的最大相交面积的格网的数据
            Map<String, Map<String, Object>> initMap = initMap1(mapList);
            Map<String, BigDecimal> detailMap = new HashMap<>();
            for (Map.Entry<String, Map<String, Object>> entry : initMap.entrySet()) {
                Map<String, Object> value = entry.getValue();
                //详表
                BigDecimal directLosses = null;
                String key1 = taskId + "-" + value.get("sort") + "-" + value.get("earthquakeLevel") + "-" + value.get("angle");
                if (detailMap.containsKey(key1)) {
                    directLosses = detailMap.get(key1);
                    directLosses = directLosses.add(BigDecimal.valueOf((Float) value.get("directLosses")));//直接经济损失和
                } else {
                    //初始化
                    directLosses = BigDecimal.valueOf((Float) value.get("directLosses"));
                }
                detailMap.put(key1, directLosses);
            }
            Map<String, ResultMainEntity> map = new HashMap<>();
            for (String key : pointDetailList) {
                String[] split = key.split("-");
                ResultDetailsEntity detailsEntity = new ResultDetailsEntity();
                detailsEntity.setTaskId(split[0]);
                detailsEntity.setSort(split[1]);
                detailsEntity.setMagnitude(new BigDecimal(split[2]+""));
                detailsEntity.setAngle(split[3]);

                BigDecimal directLosses = BigDecimal.ZERO;
                BigDecimal value = detailMap.get(key);
                if (value != null) {
                    directLosses = value.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_UP);
                }
                detailsEntity.setDisasterLoss(String.valueOf(directLosses));
                detailsEntity.setUpdateId(PlatformSessionUtils.getUserId());
                detailsEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                detailsEntity.setDataSource("2");
                resultTotalService.updateResultDetailsEntity(detailsEntity);
                //结果主表
                String key2 = split[0] + "-" + split[1] + "-" + split[2];
                ResultMainEntity resultMainEntity = null;
                if (map.containsKey(key2)) {
                    resultMainEntity = map.get(key2);
                    resultMainEntity.setDisasterLossBefore(compareTo(directLosses, resultMainEntity.getDisasterLossBefore()));
                } else {
                    resultMainEntity = new ResultMainEntity();
                    resultMainEntity.setDisasterLossBefore(directLosses + "-0");
                    map.put(key2, resultMainEntity);
                }
                map.put(key2, resultMainEntity);
            }
            resultTotalService.updateResultMainEntity(map, "6");

            byTaskId.setButton3_status2("1");
            intensityRelationService.updateSeismicIntensityRelation(byTaskId);
            System.out.println("计算格网时间花费" + (System.currentTimeMillis() - start) / 1000);
            return RestResponse.succeed("计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    private Map<String, Map<String, Object>> initMap1(List<Map<String, Object>> mapList) {
        //pbeId,area,directLosses,longitude,latitude,earthquakeLevel,angle,earthquakeId
        Map<String, Map<String, Object>> initMap = new HashMap<>();
        for (Map<String, Object> map1 : mapList) {
            String key = map1.get("pbeId") + "-" + map1.get("earthquakeId");
            if (initMap.containsKey(key)) {
                Map<String, Object> map2 = initMap.get(key);
                if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) < 0) {
                    initMap.put(key, map1);
                } else if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) == 0) {
                    if (((BigDecimal) map2.get("earthquakeLevel")).compareTo((BigDecimal) map1.get("earthquakeLevel")) < 0) {
                        initMap.put(key, map1);
                    }
                }
            } else {
                initMap.put(key, map1);
            }
        }
        return initMap;
    }

    private String compareTo(BigDecimal num1, String num2) {
        // num1:5 8 4 3
        // num2:10-0
        String[] split = num2.split("-");//5 10
        for (int i = 0; i < split.length; i++) {
            if (i == 0 && num1.compareTo(new BigDecimal(split[0])) < 0) {
                if (split.length == 2) {
                    if (new BigDecimal(split[0]).compareTo(new BigDecimal(split[1])) > 0) {
                        split[1] = String.valueOf(new BigDecimal(split[0]).setScale(0, RoundingMode.HALF_UP));
                        split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                    } else {
                        split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                        split[1] = String.valueOf(new BigDecimal(split[1]).setScale(0, RoundingMode.HALF_UP));
                    }
                } else {
                    split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                    split[1] = String.valueOf(new BigDecimal(split[1]).setScale(0, RoundingMode.HALF_UP));
                }
            } else if (i == 1 && num1.compareTo(new BigDecimal(split[1])) > 0) {
                split[0] = String.valueOf(new BigDecimal(split[0]).setScale(0, RoundingMode.HALF_UP));
                split[1] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
            }
        }
        num2 = split[0] + "-" + split[1];
        return num2;
    }

    /**
     * 获取每类建筑结构的建筑物结构经济损失和室内财产经济损失和建筑物直接经济损失
     */
    private Map<String, BigDecimal> getStructureLossess(Map<String, Object> tempMap, HouseEntity house, EconomicLosses model, BigDecimal indoorPrice) {
        Map<String, BigDecimal> map = new HashMap<>(2);
        //建筑物结构面积
        String structureType = (String) tempMap.get("structureType");
        BigDecimal basicArea = (BigDecimal) tempMap.get("basicArea");
        BigDecimal slightArea = (BigDecimal) tempMap.get("slightArea");
        BigDecimal midArea = (BigDecimal) tempMap.get("midArea");
        BigDecimal seriousArea = (BigDecimal) tempMap.get("seriousArea");
        BigDecimal damageArea = (BigDecimal) tempMap.get("damageArea");

        //各类损失比
        BigDecimal basic = new BigDecimal(0);
        BigDecimal slight = new BigDecimal(0);
        BigDecimal mid = new BigDecimal(0);
        BigDecimal serious = new BigDecimal(0);
        BigDecimal damage = new BigDecimal(0);

        //高层建筑每平米造价
        BigDecimal housePrice = null;
        if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getHighHousePrice() == null ? BigDecimal.ZERO : house.getHighHousePrice();
            basic = model.getHighBasicIntact();
            slight = model.getHighSlightDamage();
            mid = model.getHighMidDamage();
            serious = model.getHighBadDamage();
            damage = model.getHighDestory();
        } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getSteelPrice() == null ? BigDecimal.ZERO : house.getSteelPrice();
            basic = model.getSteelBasicIntact();
            slight = model.getSteelSlightIntact();
            mid = model.getSteelMidIntact();
            serious = model.getSteelBadIntact();
            damage = model.getSteelDestory();
        } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getConcretePrice() == null ? BigDecimal.ZERO : house.getConcretePrice();
            basic = model.getMultipleBasicIntact();
            slight = model.getMultipleSlightIntact();
            mid = model.getMultipleMidIntact();
            serious = model.getMultipleBadIntact();
            damage = model.getMultipleDestory();
        } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getBrickhunPrice() == null ? BigDecimal.ZERO : house.getBrickhunPrice();
            basic = model.getBrickConcreteBasicIntact();
            slight = model.getBrickConcreteSlightIntact();
            mid = model.getBrickConcreteMidIntact();
            serious = model.getBrickConcreteBadIntact();
            damage = model.getBrickConcreteDestory();
        } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getBrickPrice() == null ? BigDecimal.ZERO : house.getBrickPrice();
            basic = model.getBrickWoodBasicIntact();
            slight = model.getBrickWoodSlightIntact();
            mid = model.getBrickWoodMidIntact();
            serious = model.getBrickWoodBadIntact();
            damage = model.getBrickWoodDestory();
        } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getSoilPrice() == null ? BigDecimal.ZERO : house.getSoilPrice();
            basic = model.getSoilBasicIntact();
            slight = model.getSoilSlightIntact();
            mid = model.getSoilMidIntact();
            serious = model.getSoilBadIntact();
            damage = model.getSoilDestory();
        } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getWoodPrice() == null ? BigDecimal.ZERO : house.getWoodPrice();
            basic = model.getWoodBasicIntact();
            slight = model.getWoodSlightIntact();
            mid = model.getWoodMidIntact();
            serious = model.getWoodBadIntact();
            damage = model.getWoodDestory();
        } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getStonePrice() == null ? BigDecimal.ZERO : house.getStonePrice();
            basic = model.getStoneBasicIntact();
            slight = model.getStoneSlightIntact();
            mid = model.getStoneMidIntact();
            serious = model.getStoneBadIntact();
            damage = model.getStoneDestory();
        } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
            housePrice = house == null || house.getOtherPrice() == null ? BigDecimal.ZERO : house.getOtherPrice();
            basic = model.getOtherBasicIntact();
            slight = model.getOtherSlightIntact();
            mid = model.getOtherMidIntact();
            serious = model.getOtherBadIntact();
            damage = model.getOtherDestory();
        }
        //得到建筑物结构经济损失
        BigDecimal structureLossess = model.getStructureLossess();
        BigDecimal basicLossess = basicArea.multiply(housePrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal seriousLossess = seriousArea.multiply(housePrice).multiply(serious).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal midLossess = midArea.multiply(housePrice).multiply(mid).multiply(structureLossess).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP);
        BigDecimal slightLossess = slightArea.multiply(housePrice).multiply(slight).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal damageLossess = damageArea.multiply(housePrice).multiply(damage).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal structure = basicLossess.add(seriousLossess).add(midLossess).add(slightLossess).add(damageLossess);
        map.put("structure", structure);
        //得到建筑物室内财产经济损失
        BigDecimal basicIndoorLossess = basicArea.multiply(indoorPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal seriousIndoorLossess = seriousArea.multiply(indoorPrice).multiply(serious).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal midIndoorLossess = midArea.multiply(indoorPrice).multiply(mid).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal slightIndoorLossess = slightArea.multiply(indoorPrice).multiply(slight).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal damageIndoorLossess = damageArea.multiply(indoorPrice).multiply(damage).multiply(structureLossess).divide(new BigDecimal(10000), 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal indoor = basicIndoorLossess.add(seriousIndoorLossess).add(midIndoorLossess).add(slightIndoorLossess).add(damageIndoorLossess);
        map.put("indoor", indoor);
        BigDecimal directLossess = structure.add(indoor);
        map.put("direct", directLossess);
        return map;
    }

    private List<LossesVulnerabilityVO> rebuild(List<Vulnerability> allVulnerability) {
        List<LossesVulnerabilityVO> voList = new ArrayList<>();
        for (int i = 0; i < allVulnerability.size(); i++) {
            LossesVulnerabilityVO vo = new LossesVulnerabilityVO();
            vo.setStructureType(allVulnerability.get(i).getStructureType());
            vo.setIntensity(allVulnerability.get(i).getIntensity());
            vo.setZero(allVulnerability.get(i).getSix());
            vo.setOne(allVulnerability.get(i + 1).getSix());
            vo.setTwo(allVulnerability.get(i + 2).getSix());
            vo.setThree(allVulnerability.get(i + 3).getSix());
            vo.setFour(allVulnerability.get(i + 4).getSix());
            voList.add(vo);
            vo = new LossesVulnerabilityVO();
            vo.setStructureType(allVulnerability.get(i).getStructureType());
            vo.setIntensity(allVulnerability.get(i).getIntensity());
            vo.setZero(allVulnerability.get(i).getSeven());
            vo.setOne(allVulnerability.get(i + 1).getSeven());
            vo.setTwo(allVulnerability.get(i + 2).getSeven());
            vo.setThree(allVulnerability.get(i + 3).getSeven());
            vo.setFour(allVulnerability.get(i + 4).getSeven());
            voList.add(vo);
            vo = new LossesVulnerabilityVO();
            vo.setStructureType(allVulnerability.get(i).getStructureType());
            vo.setIntensity(allVulnerability.get(i).getIntensity());
            vo.setZero(allVulnerability.get(i).getEight());
            vo.setOne(allVulnerability.get(i + 1).getEight());
            vo.setTwo(allVulnerability.get(i + 2).getEight());
            vo.setThree(allVulnerability.get(i + 3).getEight());
            vo.setFour(allVulnerability.get(i + 4).getEight());
            voList.add(vo);
            vo = new LossesVulnerabilityVO();
            vo.setStructureType(allVulnerability.get(i).getStructureType());
            vo.setIntensity(allVulnerability.get(i).getIntensity());
            vo.setZero(allVulnerability.get(i).getNine());
            vo.setOne(allVulnerability.get(i + 1).getNine());
            vo.setTwo(allVulnerability.get(i + 2).getNine());
            vo.setThree(allVulnerability.get(i + 3).getNine());
            vo.setFour(allVulnerability.get(i + 4).getNine());
            voList.add(vo);
            vo = new LossesVulnerabilityVO();
            vo.setStructureType(allVulnerability.get(i).getStructureType());
            vo.setIntensity(allVulnerability.get(i).getIntensity());
            vo.setZero(allVulnerability.get(i).getTen());
            vo.setOne(allVulnerability.get(i + 1).getTen());
            vo.setTwo(allVulnerability.get(i + 2).getTen());
            vo.setThree(allVulnerability.get(i + 3).getTen());
            vo.setFour(allVulnerability.get(i + 4).getTen());
            voList.add(vo);
            i += 4;
        }
        return voList;
    }

//     //@Override
//     @Transactional(rollbackFor = Exception.class)
//     public void calculate11(String modeId, String taskId) throws Exception {
//         Long start = System.currentTimeMillis();
//         //获取经济损失模型
//         EconomicLosses model = economicLossesRepository.getModelById(modeId);
//         if (PlatformObjectUtils.isEmpty(model)) {
//             throw new RuntimeException("请选择经济损失模型");
//         }
//         basicDataService.deleteSettingSeismicPbeEconomicByTaskId(taskId);
//         //List<CenterResult> resultList = basicDataService.getCenterResult(taskId);
//         List<CenterResult> centerList = new ArrayList<>();
//         String pbeId = "";
//         HouseEntity house = null;
//         HosPeoEntity hosPeo = null;
//         //建筑物结构经济损失
//         BigDecimal structureTotal = new BigDecimal(0);
//         //建筑物室内财产经济损失
//         BigDecimal indoorTotal = new BigDecimal(0);
//         BigDecimal indoorProperty = new BigDecimal(0);
//         //建筑物直接经济损失
//         BigDecimal structureDirectLosses = new BigDecimal(0);
//         //经济模型系数
//         BigDecimal lifeRatio1 = model.getLifeRatio1();
//         BigDecimal lifeRatio2 = model.getLifeRatio2();
//         CenterResult centerResult = null;
//
//         List<InfluencefliedVo> vos = preAssessResultRepository.getInfluenceFieldId(taskId);
// //        List<Vulnerability> allVulnerability = basicDataService.getAllVulnerabilityByTaskId(taskId);
// //        Map<String, Vulnerability> structureAndIntensityMap = new HashMap<>();
// //        if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
// //            //<建筑物类别,<损坏,0.25>>
// //            structureAndIntensityMap = getStructureAndIntensity(allVulnerability);
// //        }
//         Map<String, List<BigDecimal>> structureAndIntensityMap = new HashMap<>();
//         basicDataService.deleteCenterResultByTaskId(taskId);
//         List<SettingSeismicDetails> settingSeismicDetails = settingSeismicService.getSettingSeismicDetailsByTaskId(taskId);
//         if (PlatformObjectUtils.isNotEmpty(settingSeismicDetails)) {
//             //最大损失
//             BigDecimal maxLosses = new BigDecimal(0);
//             //最小损失
//             BigDecimal minLosses = new BigDecimal(0);
//             //总的损失
//             BigDecimal totalLosses = new BigDecimal(0);
//             BigDecimal earthLevel = settingSeismicDetails.get(0).getEarthquakeLevel();
//             SettingSeismicDetails detail = null;
//             for (int dd = 0; dd < settingSeismicDetails.size(); dd++) {
//                 detail = settingSeismicDetails.get(dd);
//                 String macroPosition = detail.getMacroPosition();
//                 String province = "";
//                 String city = "";
//                 String country = "";
//                 if (StringUtils.isNotBlank(macroPosition)) {
//                     province = macroPosition.split(",")[0];
//                     city = macroPosition.split(",")[1];
//                     country = macroPosition.split(",")[2];
//                 }
//                 if (totalLosses.compareTo(maxLosses) > 0) {
//                     maxLosses = totalLosses;
//                 }
//                 if (totalLosses.compareTo(minLosses) < 0) {
//                     minLosses = totalLosses;
//                 }
//
//                 totalLosses = new BigDecimal(0);
//                 List<SettingSeismicInfluenceflied> influenceList = settingSeismicInfluencefliedRepository.findSettingSeismicInfluencefliedById(settingSeismicDetails.get(dd).getId());
//                 if (PlatformObjectUtils.isNotEmpty(influenceList)) {
//                     for (int bb = 0; bb < influenceList.size(); bb++) {
//                         List<Vulnerability> allVulnerability = preAssessResultService.matrixSee(province, city, country, taskId, influenceList.get(bb).getDzIntensity());
//                         if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
//                             //<建筑物类别,<损坏,0.25>>
//                             structureAndIntensityMap = getStructureAndIntensity(allVulnerability, influenceList.get(bb).getDzIntensity());
//                         }
//                         List<PbeEntity> pbeList = pbeService.getPbeByInfluenceflieId(influenceList.get(bb).getUuid());
//                         if (PlatformObjectUtils.isNotEmpty(pbeList)) {
//                             for (PbeEntity pbeEntity : pbeList) {
//                                 //地震id
//                                 String earthquakeId = influenceList.get(bb).getSourceEarthquakeId();
//                                 //影响场id
//                                 String influenceflieId = influenceList.get(bb).getUuid();
//                                 //格网id
//                                 String id = pbeEntity.getPbeId();
//                                 //获取格网下的面积
//                                 BigDecimal area = new BigDecimal(pbeEntity.getCoveredarea());
//                                 if (area.compareTo(new BigDecimal(0)) == 0) {
//                                     continue;
//                                 }
//                                 BigDecimal hRatio = new BigDecimal(0);
//                                 BigDecimal steelRatio = new BigDecimal(0);
//                                 BigDecimal cRatio = new BigDecimal(0);
//                                 BigDecimal bRatio = new BigDecimal(0);
//                                 BigDecimal bmRatio = new BigDecimal(0);
//                                 BigDecimal sRatio = new BigDecimal(0);
//                                 BigDecimal wRatio = new BigDecimal(0);
//                                 BigDecimal stRatio = new BigDecimal(0);
//                                 BigDecimal oRatio = new BigDecimal(0);
//
//                                 StructuralProportionVo structuralProportion = preAssessResultService.getStructuralProportion(pbeEntity);
//                                 if (PlatformObjectUtils.isNotEmpty(structuralProportion)) {
//                                     if ("城镇".equals(pbeEntity.getTownorcontry())) {
//                                         hRatio = structuralProportion.getDhpTownHighTatio();
//                                         steelRatio = structuralProportion.getDhpTownSteelTatio();
//                                         cRatio = structuralProportion.getDhpTownBetonTatio();
//                                         bRatio = structuralProportion.getDhpTownBrickTatio();
//                                         bmRatio = structuralProportion.getDhpTownMasonryTatio();
//                                         sRatio = structuralProportion.getDhpTownSoilTatio();
//                                         wRatio = structuralProportion.getDhpTownWoodTatio();
//                                         stRatio = structuralProportion.getDhpTownStoneTatio();
//                                         oRatio = structuralProportion.getDhpTownOtherTatio();
//                                     } else if ("农村".equals(pbeEntity.getTownorcontry())) {
//                                         hRatio = structuralProportion.getDhpVillageHighTatio();
//                                         steelRatio = structuralProportion.getDhpVillageSteelTatio();
//                                         cRatio = structuralProportion.getDhpVillageBetonTatio();
//                                         bRatio = structuralProportion.getDhpVillageBrickTatio();
//                                         bmRatio = structuralProportion.getDhpVillageMasonryTatio();
//                                         sRatio = structuralProportion.getDhpVillageSoilTatio();
//                                         wRatio = structuralProportion.getDhpVillageWoodTatio();
//                                         stRatio = structuralProportion.getDhpVillageStoneTatio();
//                                         oRatio = structuralProportion.getDhpVillageOtherTatio();
//                                     }
//                                 } else {
//                                     throw new RuntimeException("获取不到对应的建筑物比例");
//                                 }
//                                 //拿到格网下的每类建筑物的占比窃取每类建筑物的面积
//                                 //假设面积比例
//                                 //高层建筑 0.1
//                                 BigDecimal hArea = area.multiply(hRatio);
//                                 //钢结构 0.1
//                                 BigDecimal steelArea = area.multiply(steelRatio);
//                                 //多层钢筋混凝土结构 0.2
//                                 BigDecimal cArea = area.multiply(cRatio);
//                                 ;
//                                 //砖混结构 0.15
//                                 BigDecimal bArea = area.multiply(bRatio);
//                                 ;
//                                 //砖木结构 0.15
//                                 BigDecimal bmArea = area.multiply(bmRatio);
//                                 ;
//                                 //土结构 0.15
//                                 BigDecimal sArea = area.multiply(sRatio);
//                                 ;
//                                 //木结构 0.1
//                                 BigDecimal wArea = area.multiply(wRatio);
//                                 ;
//                                 //石结构 0.1
//                                 BigDecimal stArea = area.multiply(stRatio);
//                                 ;
//                                 //其他结构 0.05
//                                 BigDecimal oArea = area.multiply(oRatio);
//                                 ;
//                                 //拿到建筑物易损性信息求取该格网下每类建筑物的易损面积
//                                 //总的损坏面积=各类建筑类别的损坏面积之和
//                                 BigDecimal totalDdArea = new BigDecimal(0);
//
//                                 house = houseService.getHouse(pbeEntity.getProvince(), pbeEntity.getCity(), pbeEntity.getCounty());
//                                 hosPeo = hosPeoRepository.findHosPeo(pbeEntity.getProvince(), pbeEntity.getCity(), pbeEntity.getCounty());
//                                 if (house == null) {
//                                     throw new RuntimeException("查询不到房屋造价信息");
//                                 }
//                                 if (hosPeo == null) {
//                                     throw new RuntimeException("查询不到人口和建筑物概况信息");
//                                 }
//                                 if ("城镇".equals(pbeEntity.getTownorcontry())) {
//                                     indoorProperty = hosPeo.getDhpTownIndoorProperty();
//                                 } else if ("农村".equals(pbeEntity.getTownorcontry())) {
//                                     indoorProperty = hosPeo.getDhpVillageIndoorProperty();
//                                 }
//                                 if (structureAndIntensityMap.size() > 0) {
//                                     Iterator<Map.Entry<String, List<BigDecimal>>> iterator = structureAndIntensityMap.entrySet().iterator();
//                                     while (iterator.hasNext()) {
//                                         BigDecimal temp = new BigDecimal(0);
//                                         Map.Entry<String, List<BigDecimal>> next = iterator.next();
//                                         String structureType = next.getKey();
//                                         List<BigDecimal> vulnerability = next.getValue();
//                                         BigDecimal basic = null;
//                                         BigDecimal slight = null;
//                                         BigDecimal mid = null;
//                                         BigDecimal serious = null;
//                                         BigDecimal damage = null;
//                                         CenterResult result = new CenterResult();
//                                         if (PlatformObjectUtils.isNotEmpty(vulnerability)) {
//                                             basic = vulnerability.get(0);
//                                             slight = vulnerability.get(1);
//                                             mid = vulnerability.get(2);
//                                             serious = vulnerability.get(3);
//                                             damage = vulnerability.get(4);
//                                             if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
//                                                 temp = hArea;
//                                             } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
//                                                 temp = steelArea;
//                                             } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
//                                                 temp = cArea;
//                                             } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
//                                                 temp = bArea;
//                                             } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
//                                                 temp = bmArea;
//                                             } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
//                                                 temp = sArea;
//                                             } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
//                                                 temp = wArea;
//                                             } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
//                                                 temp = sArea;
//                                             } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
//                                                 temp = oArea;
//                                             }
//                                             //获取不同破损程度下的不同建筑物类别的面积
//                                             //基本完好
//                                             BigDecimal bdArea = basic.compareTo(new BigDecimal(0.00)) == 0 ? basic : basic.multiply(temp);
//                                             //轻微破坏
//                                             BigDecimal sdArea = slight.compareTo(new BigDecimal(0.00)) == 0 ? slight : slight.multiply(temp);
//                                             //中等破坏
//                                             BigDecimal mdArea = mid.compareTo(new BigDecimal(0.00)) == 0 ? mid : mid.multiply(temp);
//                                             //严重破坏
//                                             BigDecimal sedArea = serious.compareTo(new BigDecimal(0.00)) == 0 ? serious : serious.multiply(temp);
//                                             //损坏
//                                             BigDecimal ddArea = damage.compareTo(new BigDecimal(0.00)) == 0 ? damage : damage.multiply(temp);
//                                             totalDdArea = totalDdArea.add(ddArea);
//                                             //保存计算中间结果
//                                             result.setTaskId(taskId);
//                                             result.setEarthquakeId(earthquakeId);
//                                             result.setInfluenceflieId(influenceflieId);
//                                             result.setPbeId(id);
//                                             result.setStructureType(structureType);
//                                             result.setBasicArea(bdArea);
//                                             result.setBasic(basic);
//                                             result.setSlightArea(sdArea);
//                                             result.setSlight(slight);
//                                             result.setMidArea(mdArea);
//                                             result.setMid(mid);
//                                             result.setSeriousArea(sedArea);
//                                             result.setSerious(serious);
//                                             result.setDamageArea(ddArea);
//                                             result.setDamage(damage);
//                                             result.setArea(area);
//                                             result.setPopulation(new BigDecimal(pbeEntity.getPopulation()));
//                                             centerList.add(result);
//                                             //保存中间结果
//                                             //basicDataService.save(result);
//                                             //resultList.add(result);
//                                         }
//                                         //每一类建筑物在不同破坏程度下的破坏面积
//                                         Map<String, BigDecimal> losses = getStructureLossess(result, house, model, indoorProperty);
//                                         //建筑物结构经济损失
//                                         structureTotal = structureTotal.add(losses.get("structure"));
//                                         //建筑物室内财产经济损失
//                                         indoorTotal = structureTotal.add(losses.get("indoor"));
//                                         //建筑物直接经济损失
//                                         structureDirectLosses = structureTotal.add(indoorTotal);
//
//                                     }
//
//                                     TaskPbeEconomic taskPbe = new TaskPbeEconomic();
//                                     taskPbe.setUuid(UUIDGenerator.getUUID());
//                                     taskPbe.setTaskId(taskId);
//                                     taskPbe.setEarthquakeId(influenceList.get(bb).getSourceEarthquakeId());
//                                     taskPbe.setInfluencefliedId(influenceList.get(bb).getUuid());
//                                     taskPbe.setPbeId(String.valueOf(pbeEntity.getPbeId()));
//                                     taskPbe.setStructureLosses(structureTotal);
//                                     taskPbe.setIndoorLosses(indoorTotal);
//                                     taskPbe.setStructureDirectLosses(structureDirectLosses);
//                                     BigDecimal lifeLosses = structureDirectLosses.divide(lifeRatio1, 2, BigDecimal.ROUND_HALF_UP).multiply(lifeRatio2);
//                                     taskPbe.setLifeLosses(lifeLosses);
//                                     BigDecimal otherLosses = structureDirectLosses.divide(model.getOtherRatio1(), 2, BigDecimal.ROUND_HALF_UP).multiply(model.getOtherRatio2());
//                                     taskPbe.setOtherLosses(otherLosses);
//                                     BigDecimal directLosses = structureDirectLosses.add(lifeLosses).add(otherLosses);
//                                     taskPbe.setDirectLosses(directLosses);
//                                     totalLosses = totalLosses.add(directLosses);
//                                     basicDataService.insertTaskPbeEconomic(taskPbe);
//                                 }
//
//                             }
//                         }
//                     }
//                 }
//                 if (dd == 0) {
//                     maxLosses = totalLosses;
//                     minLosses = totalLosses;
//                 }
//                 ResultDetailsEntity resultDetailsEntity = new ResultDetailsEntity();
//                 resultDetailsEntity.setTaskId(taskId);
//                 resultDetailsEntity.setLongitude(settingSeismicDetails.get(dd).getLongitude().toString());
//                 resultDetailsEntity.setLatitude(settingSeismicDetails.get(dd).getLatitude().toString());
//                 resultDetailsEntity.setMagnitude(settingSeismicDetails.get(dd).getEarthquakeLevel());
//                 resultDetailsEntity.setDisasterLoss(String.valueOf(totalLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP)));
//                 resultDetailsEntity.setDataSource("2");
//                 resultDetailsEntity.setAngle(String.valueOf(settingSeismicDetails.get(dd).getAngle()));
//                 resultTotalRepository.updateResultDetailsEntity(resultDetailsEntity);
//
//                 if (!settingSeismicDetails.get(dd).getEarthquakeLevel().equals(earthLevel)) {
//                     ResultMainEntity resultMainEntity = new ResultMainEntity();
//                     resultMainEntity.setTaskId(taskId);
//                     resultMainEntity.setLongitude(settingSeismicDetails.get(dd - 1).getLongitude().toString());
//                     resultMainEntity.setLatitude(settingSeismicDetails.get(dd - 1).getLatitude().toString());
//                     resultMainEntity.setMagnitude(settingSeismicDetails.get(dd - 1).getEarthquakeLevel());
//                     resultMainEntity.setDisasterLossBefore(minLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP) + "-" + maxLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP));
//                     resultMainEntity.setDisasterLossAfter(minLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP) + "-" + maxLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP));
//                     resultMainEntity.setDataSource("2");
//                     resultTotalRepository.updateResultTotal(resultMainEntity);
//                     maxLosses = totalLosses;
//                     minLosses = totalLosses;
//                     earthLevel = settingSeismicDetails.get(dd).getEarthquakeLevel();
//                     System.out.println(resultMainEntity);
//                 }
//             }
//             if (totalLosses.compareTo(maxLosses) > 0) {
//                 maxLosses = totalLosses;
//             }
//             if (totalLosses.compareTo(minLosses) < 0) {
//                 minLosses = totalLosses;
//             }
//             ResultMainEntity resultMainEntity = new ResultMainEntity();
//             resultMainEntity.setTaskId(taskId);
//             resultMainEntity.setLongitude(detail.getLongitude().toString());
//             resultMainEntity.setLatitude(detail.getLatitude().toString());
//             resultMainEntity.setMagnitude(detail.getEarthquakeLevel());
//             resultMainEntity.setDataSource("2");
//             resultMainEntity.setDisasterLossBefore(minLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP) + "-" + maxLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP));
//             resultMainEntity.setDisasterLossAfter(minLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP) + "-" + maxLosses.divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP));
//             resultTotalRepository.updateResultTotal(resultMainEntity);
//         }
//         if (PlatformObjectUtils.isNotEmpty(centerList)) {
//             for (CenterResult result : centerList) {
//                 basicDataService.save(result);
//             }
//         }
//         Long end = System.currentTimeMillis();
//         System.out.println("总消耗时间是:" + (end - start) / 1000);
//     }


    //    private Map<String, Vulnerability> getStructureAndIntensity(List<Vulnerability> allVulnerability) {
//        Map<String, Vulnerability> map = new HashMap<>();
//        for (Vulnerability taskVulnerability : allVulnerability) {
//            String structureType = taskVulnerability.getStructureType();
//            map.put(structureType,taskVulnerability);
//        }
//        return map;
//    }
    private Map<String, List<BigDecimal>> getStructureAndIntensity(List<Vulnerability> allVulnerability, String dzIntensity) {
        //Map<String, Vulnerability> map = new HashMap<>();
        Map<String, List<BigDecimal>> map = new HashMap<>();
        List<BigDecimal> dataList = new ArrayList<>();
        for (Vulnerability taskVulnerability : allVulnerability) {
            String structureType = taskVulnerability.getStructureType();
            if (!map.containsKey(structureType)) {
                dataList = new ArrayList<>();
            }
            if ("6".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getSix());
            } else if ("7".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getSeven());
            } else if ("8".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getEight());
            } else if ("9".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getNine());
            } else if ("10".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getTen());
            }
            map.put(structureType, dataList);
        }
        return map;
    }

    private Map<String, BigDecimal> getStructureLossess(CenterResult result, HouseEntity house, EconomicLosses model, BigDecimal indoorPrice) {
        Map<String, BigDecimal> map = new HashMap<>(2);
        //建筑物结构
        String structureType = result.getStructureType();
        BigDecimal basicArea = result.getBasicArea();
        BigDecimal slightArea = result.getSlightArea();
        BigDecimal midArea = result.getMid();
        BigDecimal seriousArea = result.getSeriousArea();
        BigDecimal damageArea = result.getDamageArea();

        //各类损失比
        BigDecimal basic = new BigDecimal(0);
        ;
        BigDecimal slight = new BigDecimal(0);
        ;
        ;
        BigDecimal mid = new BigDecimal(0);
        ;
        ;
        BigDecimal serious = new BigDecimal(0);
        ;
        ;
        BigDecimal damage = new BigDecimal(0);
        ;
        ;
        //高层建筑每平米造价
        BigDecimal housePrice = null;
        if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
            housePrice = house.getHighHousePrice();
            basic = model.getHighBasicIntact();
            slight = model.getHighSlightDamage();
            mid = model.getHighMidDamage();
            serious = model.getHighBadDamage();
            damage = model.getHighDestory();
        } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
            housePrice = house.getSteelPrice();
            basic = model.getSteelBasicIntact();
            slight = model.getSteelSlightIntact();
            mid = model.getSteelMidIntact();
            serious = model.getSteelBadIntact();
            damage = model.getSteelDestory();
        } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
            housePrice = house.getConcretePrice();
            basic = model.getMultipleBasicIntact();
            slight = model.getMultipleSlightIntact();
            mid = model.getMultipleMidIntact();
            serious = model.getMultipleBadIntact();
            damage = model.getMultipleDestory();
        } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
            housePrice = house.getBrickhunPrice();
            basic = model.getBrickConcreteBasicIntact();
            slight = model.getBrickConcreteSlightIntact();
            mid = model.getBrickConcreteMidIntact();
            serious = model.getBrickConcreteBadIntact();
            damage = model.getBrickConcreteDestory();
        } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
            housePrice = house.getBrickPrice();
            basic = model.getBrickWoodBasicIntact();
            slight = model.getBrickWoodSlightIntact();
            mid = model.getBrickWoodMidIntact();
            serious = model.getBrickWoodBadIntact();
            damage = model.getBrickWoodDestory();
        } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
            housePrice = house.getSoilPrice();
            basic = model.getSoilBasicIntact();
            slight = model.getSoilSlightIntact();
            mid = model.getSoilMidIntact();
            serious = model.getSoilBadIntact();
            damage = model.getSoilDestory();
        } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
            housePrice = house.getWoodPrice();
            basic = model.getWoodBasicIntact();
            slight = model.getWoodSlightIntact();
            mid = model.getWoodMidIntact();
            serious = model.getWoodBadIntact();
            damage = model.getWoodDestory();
        } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
            housePrice = house.getStonePrice();
            basic = model.getStoneBasicIntact();
            slight = model.getStoneSlightIntact();
            mid = model.getStoneMidIntact();
            serious = model.getStoneBadIntact();
            damage = model.getStoneDestory();
        } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
            housePrice = house.getOtherPrice();
            basic = model.getOtherBasicIntact();
            slight = model.getOtherSlightIntact();
            mid = model.getOtherMidIntact();
            serious = model.getOtherBadIntact();
            damage = model.getOtherDestory();
        }
        //得到建筑物结构经济损失
        BigDecimal structureLossess = model.getStructureLossess();
        BigDecimal basicLossess = basicArea.multiply(housePrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal seriousLossess = seriousArea.multiply(housePrice).multiply(serious).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal midLossess = midArea.multiply(housePrice).multiply(mid).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal slightLossess = slightArea.multiply(housePrice).multiply(slight).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal damageLossess = damageArea.multiply(housePrice).multiply(damage).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal structure = basicLossess.add(seriousLossess).add(midLossess).add(slightLossess).add(damageLossess);
        map.put("structure", structure);
        //得到建筑物室内财产经济损失
        BigDecimal basicIndoorLossess = basicArea.multiply(indoorPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal seriousIndoorLossess = seriousArea.multiply(indoorPrice).multiply(serious).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal midIndoorLossess = midArea.multiply(indoorPrice).multiply(mid).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal slightIndoorLossess = slightArea.multiply(indoorPrice).multiply(slight).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal damageIndoorLossess = damageArea.multiply(indoorPrice).multiply(damage).multiply(structureLossess).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal indoor = basicIndoorLossess.add(seriousIndoorLossess).add(midIndoorLossess).add(slightIndoorLossess).add(damageIndoorLossess);
        map.put("indoor", indoor);
        return map;
    }


    private EconomicLosses resetSasualty(EconomicLosses economicLosses) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        economicLosses.setProvince(areaMap.get(economicLosses.getProvince()));
        if (!"全部".equals(economicLosses.getCity())) {
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(economicLosses.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            economicLosses.setCity(cityName.substring(0, cityName.length() - 1));
        }
        return economicLosses;
    }

    @Override
    public List<DataPbeLosses> getPbeByTaskIdAndIntensity(String taskId, String dzIntensity) {
        List<DataPbeLosses> pbeList = economicLossesRepository.getPbeLosses(taskId, dzIntensity);
        return pbeList;
    }

    //ss
    @Override
    public EconomicLosses getModel1ById(String id) {
        EconomicLosses economicLosses = economicLossesRepository.getModelById(id);
        return economicLosses;
    }

    @Override
    public DataPbeLosses findByTaskIdLimit(String taskId) {
        return economicLossesRepository.findByTaskIdLimit(taskId);
    }

    //生成shp文件
    private void buildData(List<DataPbeLosses>  dataList,long postName) throws Exception {
        String filePath = localDir+File.separator+"各个烈度经济损失情况" +postName+ ".shp";
        File file = new File(filePath);
        ShapefileDataStoreFactory sf = new ShapefileDataStoreFactory();
        ShapefileDataStore ds = (ShapefileDataStore) sf.createDataStore(file.toURI().toURL());
        ds.setCharset(Charset.forName("GBK"));
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        tb.setCRS(CRS.decode("EPSG:4490"));
        tb.setName("shapefile");
        tb.add("烈度", String.class);
        tb.add("建筑面积", BigDecimal.class);
        tb.add("人口", BigDecimal.class);
        tb.add("建筑物结构损失", BigDecimal.class);
        tb.add("室内损失", BigDecimal.class);
        tb.add("建筑物直接经济损失", BigDecimal.class);
        tb.add("生命线损失", BigDecimal.class);
        tb.add("其他损失", BigDecimal.class);
        tb.add("直接经济损失", BigDecimal.class);
        tb.add("the_geom", MultiPolygon.class);
        SimpleFeatureType simpleFeatureType = tb.buildFeatureType();
        ds.createSchema(simpleFeatureType);
        FeatureWriter featureWriter = ds.getFeatureWriter(ds.getTypeNames()[0], null);
        for (DataPbeLosses seiCapDistribution : dataList) {
            SimpleFeature feature = (SimpleFeature) featureWriter.next();
            feature.setAttribute(1, seiCapDistribution.getDzIntentity());
            feature.setAttribute(2, seiCapDistribution.getCoveredarea());
            feature.setAttribute(3, seiCapDistribution.getPopulation());
            feature.setAttribute(4, seiCapDistribution.getStructureLosses());
            feature.setAttribute(5, seiCapDistribution.getIndoorLosses());
            feature.setAttribute(6, seiCapDistribution.getStructureDirectLosses());
            feature.setAttribute(7, seiCapDistribution.getLifeLosses());
            feature.setAttribute(8, seiCapDistribution.getOtherLosses());
            feature.setAttribute(9, seiCapDistribution.getDirectLosses());
            String geom =  seiCapDistribution.getGeomText();
            feature.setAttribute("the_geom", geom);
        }
        featureWriter.write();
        featureWriter.close();
        ds.dispose();
    }
    @Override
    public void exportPbeInjuries(String taskId, HttpServletResponse resp) throws Exception{
        List<DataPbeLosses> dataList = economicLossesRepository.getPbeLosses(taskId, "");
        if(PlatformObjectUtils.isEmpty(dataList) || dataList.size()==0){
            throw new RuntimeException("导出失败，未查询到各个烈度下的经济损失数据");
        }
        long postName = System.currentTimeMillis();
        buildData(dataList,postName);
        String zipPath = localDir +File.separator+ "各个烈度经济损失情况"+System.currentTimeMillis()+ ".zip";
        InputStream input = null;
        ZipOutputStream zipOut = null;

        File zipFile = new File(zipPath);
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            // zip的名称为
            zipOut.setComment("各个烈度经济损失情况");
            String[] shpFiles = new String[]{
                    localDir + File.separator  + "各个烈度经济损失情况"+postName+".dbf",
                    localDir + File.separator  + "各个烈度经济损失情况"+postName+".prj",
                    localDir + File.separator  + "各个烈度经济损失情况"+postName+".shp",
                    localDir + File.separator  + "各个烈度经济损失情况"+postName+".shx",
                    localDir + File.separator  + "各个烈度经济损失情况"+postName+".fix"
            };
            for (int i = 0; i < shpFiles.length; i++) {
                File file1 = new File(shpFiles[i]);
                input = new FileInputStream(file1);
                zipOut.putNextEntry(new ZipEntry(file1.getName()));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
            }
            for (String shpFile : shpFiles) {
                //删除生成的临时文件
                File file1 = new File(shpFile);
                file1.deleteOnExit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        export(zipFile,resp);
    }
    private void export(File zipFile, HttpServletResponse response) throws IOException {
        InputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(zipFile.getName(), "UTF-8"));
        response.setHeader("Access-Control-Allow-Origin","*");
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        os.write(buffer);// 输出文件
        os.flush();
        os.close();
    }
}
